package com.jy.oms.framework.asyn.task.util;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.jy.oms.framework.asyn.task.exception.TaskConfigException;
import com.jy.oms.framework.thread.CustomThreadPoolExecutor;
import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.LazyInitializer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * common threadpool
 *
 * @author liuquan
 */
public final class TaskCommonThreadPool {

    private final LazyInitializer<ThreadPoolExecutor> executorLazyInitializer =
            new LazyInitializer<ThreadPoolExecutor>() {
                @Override
                protected ThreadPoolExecutor initialize() throws ConcurrentException {
                    CustomThreadPoolExecutor threadPoolExecutor = new CustomThreadPoolExecutor(
                            "AsyncTaskCommonThreadPool",
                            5, 10, 30L, TimeUnit.MINUTES,
                            new ArrayBlockingQueue<>(2000),
                            ThreadFactoryBuilder.create().setNamePrefix("aync_task_common_").build());
                    threadPoolExecutor.allowCoreThreadTimeOut(true);
                    return threadPoolExecutor;
                }
            };

    private static TaskCommonThreadPool instance = new TaskCommonThreadPool();

    public static TaskCommonThreadPool getInstance(){
        return instance;
    }

    public void execute(Runnable runnable) {
        try {
            executorLazyInitializer.get().execute(runnable);
        } catch (ConcurrentException e) {
            throw new TaskConfigException(e);
        }
    }
}
